package com.bstek.uflo.designer.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.bstek.dorado.web.resolver.AbstractResolver;
import com.bstek.uflo.designer.utils.FileUtils;

/**
 * 
 * @author matt.yao@bstek.com
 * @since 1.0
 * 
 */
public class UploadFileResolver extends AbstractResolver {
	@Override
	protected ModelAndView doHandleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			doUpload(request, response);
		} catch (Exception e) {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(e.getMessage());
		}
		return null;
	}

	private void doUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		MultipartHttpServletRequest multiPartReq = null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
		if (!(request instanceof MultipartHttpServletRequest) && multipartResolver.isMultipart(request)) {
			multiPartReq = multipartResolver.resolveMultipart(request);
		} else if (request instanceof MultipartHttpServletRequest) {
			multiPartReq = (MultipartHttpServletRequest) request;
		}
		if (multiPartReq != null) {
			MultipartFile multipartFile = multiPartReq.getFile("file");
			String name = multipartFile.getOriginalFilename();
			if (name.endsWith(".xml")) {
				InputStream input = multipartFile.getInputStream();
				String fileKey = UUID.randomUUID().toString();
				File fileLocation = new File(FileUtils.getTempDirectory(), fileKey + ".uflo.xml");
				FileOutputStream output = new FileOutputStream(fileLocation);
				try {
					IOUtils.copy(input, output);
					FileKeyManager.putFileKey(fileKey, fileLocation.getAbsolutePath());
					response.getWriter().print("{key:'" + fileKey + "'}");
				} finally {
					IOUtils.closeQuietly(input);
					IOUtils.closeQuietly(output);
				}
			}
		}
	}
}
